import {Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {MessageService} from '../../../../services/system/message.service';
import {ObjectUtil} from '../../../utils/object-util';
import {DhlCommonInputComponent} from '../dhlCommonInput';
import {UploadType} from '../enums';

@Component({
  selector: 'dhl-upload',
  templateUrl: './dhl-upload.component.html'
})
export class DhlUploadComponent extends DhlCommonInputComponent implements OnInit {


  showUploadList = {
    showPreviewIcon: true,
    showRemoveIcon: true,
    hidePreviewIconInNonImage: true
  };
  previewImage = '';
  previewVisible = false;
  downloadIcon = '<i nz-icon="" ng-reflect-nz-type="download" class="anticon ng-tns-c269-35 anticon-delete ng-star-inserted" style="display: inline-block;"><svg viewBox="64 64 896 896" fill="currentColor" width="1em" height="1em" data-icon="download" aria-hidden="true"><path d="M505.7 661a8 8 0 0012.6 0l112-141.7c4.1-5.2.4-12.9-6.3-12.9h-74.1V168c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v338.3H400c-6.7 0-10.4 7.7-6.3 12.9l112 141.8zM878 626h-60c-4.4 0-8 3.6-8 8v154H214V634c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v198c0 17.7 14.3 32 32 32h684c17.7 0 32-14.3 32-32V634c0-4.4-3.6-8-8-8z"></path></svg></i>';
  textThum = 'data:text/plain;base64,19S2r8ztvNNjcmVhdHVzZXK4xM6qZW1wbm8=';
  fileList = [];
  loading = false;
  avatarUrl: string;
  multipleLimit = 0;
  isMultiple = false;
  tempMapFilePosition = 0
  positionIndex = 0;
  fileSize = 100 * 1024;
  uploadUrl = this.commonService.getRequestUrl('attachment/upload');
  downloadUrl = 'attachment/download';


  // 上传文件大小单位M
  @Input() set size(value) {
    this.fileSize = value * 1024;
  }

  @Input() set uploadPath(value) {
    this.uploadUrl = this.commonService.getRequestUrl(value);
  }

  @Input() set downloadPath(value) {
    this.downloadUrl = value;
  }


  // 一次性上传文件数量
  @Input() set limit(value) {
    this.multipleLimit = value;
    if (value > 0) {
      this.isMultiple = true;
    } else {
      this.isMultiple = false;
    }
  }


  @Input() btnSizeType;
  @Input() params = {};
  @Input() type = UploadType.CARD;
  // 累计上传文件数量
  @Input() max = 1;
  @Input() accept;
  @Input() readonly = false;
  @ViewChild('uploadBtnRef', {static: true, read: ElementRef}) uploadBtnRef: ElementRef;
  @Output() startUpload = new EventEmitter();
  @Output() endUpload = new EventEmitter();

  constructor(private message: MessageService) {
    super();
  }

  onRemove = () => {
    const removedFileIds = this.fileList.filter(p => p.status == 'removed').map(p => p.response ? p.response.data.id + '' : p.uid + '');
    const newInputV = [];
    for (const item of this.inputValue) {
      for (const id of removedFileIds) {
        if (item + '' == id + '') {
          // this.requestService.post(`attachment/delete/${id}`).subscribe();
          continue;
        }
        newInputV.push(item);
      }
    }
    this.inputValue = newInputV;
    return true;
  };

  ngOnInit() {
    setTimeout(() => {
      if (this.uploadBtnRef) {
        $('nz-upload-list', this.uploadBtnRef.nativeElement).css('display', 'none');
      }
    }, 10);
  }

  valueInit(value) {
    if (ObjectUtil.isArray(value) && value.length > 0) {

      this.requestService.post('attachment/files', {ids: value}).subscribe(data => {
        if (data) {
          this.inputValue = data.map(p => p.id);
          this.fileList = data.map((item, index) => {
            const imgUrl = this.requestService.getRequestUrl(`${this.downloadUrl}/${item.id}`);
            const fileConfig = {
              uid: item.id,
              name: item.fileName,
              status: 'done',
              url: imgUrl
            };
            if (item.type != 'jpg' && item.type != 'png' && item.type != 'jpeg') {
              // @ts-ignore
              fileConfig.thumbUrl = this.textThum;
            }
            return fileConfig;
          });

          setTimeout(() => {
            $('.ant-upload-list-item-done', this.inputControl.nativeElement).each((x, uploadItem) => {
              const $icon = $(this.downloadIcon);
              $icon.on('click', () => {
                this.requestService.download(`${this.downloadUrl}/${this.fileList[x].uid}`, this.params);
              });

              if (this.readonly) {
                $('.ant-upload-list-item-actions > i.anticon-delete', uploadItem).remove();
              }
              $('.ant-upload-list-item-actions', uploadItem).append($icon);

              /*$(uploadItem).append(`<div class="upload-picture-text">${this.fileList[x].name}</div>`);
              const parentDiv = $(uploadItem).parent();
              const temObj = $('<div style="float: left;height: 150px; display: inline-block;"></div>');
              temObj.append($(uploadItem));
              parentDiv.append(temObj);*/
            });
          }, 10);
        } else {
          this.inputValue = [];
        }
      });
    } else {
      this.inputValue = [];
      this.fileList = [];
    }
  }


  handlePreview = (file) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
    setTimeout(() => {
      $('nz-modal > div > div > div > div > div > img:only-child')
        .parents('div.cdk-overlay-pane')
        .attr('style', 'z-index:1100');
    }, 10);
  };


  private getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result.toString()));
    reader.readAsDataURL(img);
  }

  handleChange(info: { file }): void {
    switch (info.file.status) {
      case 'uploading':
        this.startUpload.emit(info.file);
        this.loading = true;
        break;
      case 'done':
        this.endUpload.emit(info.file);
        this.loading = false;

        const {file: {response: {code, msg}}} = info;
        if (code < 0) {
          this.fileList.push();
          this.message.error(msg);
          return;
        }


        this.getBase64(info.file.originFileObj, (img: string) => {
          this.avatarUrl = img;
        });
        const {data} = info.file.response;

        const l = $('.ant-upload-list-item-uploading', this.inputControl.nativeElement).length;

        if (l > this.tempMapFilePosition) {
          this.tempMapFilePosition = l;
        }


        if (data) {
          this.inputValue = [...this.inputValue, data.id + ''];
         /* if (data) {
            const doneItems = $('div.ant-upload-list-item:eq(' + this.positionIndex++ + ')', this.inputControl.nativeElement);
            doneItems.append(`<div class="upload-picture-text">${data.fileName}</div>`);
          }*/
        }

        break;
      case 'error':
        let {message} = info.file;
        this.endUpload.emit({response: {code: 'error', msg: '后台异常'}});
        message = message == 'OK' ? '后台异常' : message;
        this.message.notifyError(message, '上传失败');
        this.loading = false;
        break;
    }
  }

  beforeUpload = () => {
    this.tempMapFilePosition = 0;
  }


}

